#include "head.h"


extern int global_thread_num;   
extern int global_server_log_fd;
extern char global_ip[20];      
extern char global_port[20];    
int main(){

    config_init();
    printf("ip = %s\n port=%s\n num=%d\n", global_ip,global_port,global_thread_num);

    //创建记录线程池相关属性的对象, 并且初始化
    thread_pool_t thread_p;
    init_thread_pool(&thread_p, global_thread_num);

    //创建tcp监听
    int socketFD;
    tcp_init(&socketFD, global_ip, global_port);

    //加入epoll监听
    int epollFD = epoll_create(1);
    epoll_add(epollFD, socketFD);

    //循环处理外部连接
    while(1){
        
        //定义一个epoll监听的就绪队列
        struct epoll_event ev[10];
        //开始epoll监听
        int ready_num = epoll_wait(epollFD, ev, 10, -1);

        //监听到活跃的文件描述符
        for(int i = 0; i < ready_num; i++){
            //监听到全连接队列中有任务接入
            if(ev[i].data.fd == socketFD){

                int netFD = accept(socketFD, NULL, NULL);
                ERROR_CHECK(netFD, -1, "accept_main.c");
                //操作临界资源加锁
                int ret = pthread_mutex_lock(&(thread_p.lock));
                ERROR_CHECK(ret, -1, "pthread_mutex_lock_main.c");

                //加入队列
                enqueue(&(thread_p.queue), netFD);

                //唤醒线程去完成任务
                ret = pthread_cond_signal(&(thread_p.cond));
                ERROR_CHECK(ret, -1, "pthread_cond_signal_main.c");

                //解锁
                ret = pthread_mutex_unlock(&(thread_p.lock));
                ERROR_CHECK(ret, -1, "pthread_mutex_unlock_main.c");
                
            }
        }
    }

    return 0;
}

